package com.vchello.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.vchello.bean.security.UserRole;
import com.vchello.bean.user.Invitation;
import com.vchello.bean.user.User;
import com.vchello.controller.constants.SubjectAttrConstants;
import com.vchello.service.message.MessageService;
import com.vchello.service.security.UserRoleService;
import com.vchello.service.user.InvitationService;
import com.vchello.service.user.UserService;
import com.vchello.util.ToolUtil;
import com.vchello.util.Utility;

@Controller
public class LoginController extends BaseController {
	
	private static final String USER_NULL = "0";      //该账户不存在
	private static final String PASSWORD_ERROR = "1"; //密码不正确
	private static final String SUCCESS = "2";        //登录成功

	@Autowired
	private UserService userService;
	@Autowired
	private InvitationService invitationService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private MessageService messageService;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(){
		return "login";
		
	}

	/**
	 * @param phone
	 * @param password
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void login(String phone, String password, @RequestParam(value="code", required=false) String code) {
		
		try {
			Subject subject = SecurityUtils.getSubject();
			
			AuthenticationToken token = createToken(request);
			subject.login(token);
			
			User user = null;
			user = userService.findUserByPhone(phone);
			if(null == user){
				error(USER_NULL);
				return;
			}
			
			
			user = userService.login(phone, password);
			if(null == user) {
				error(PASSWORD_ERROR);
				return;
			}
			saveInvitation(code, user.getId());
			user.setLastLoginTime(Utility.getSimpleFormatedDayNow());
			userService.updateUser(user);
			session.setAttribute(SubjectAttrConstants.USER_AWARE_CONSTANT, user);
			session.setAttribute(SubjectAttrConstants.MESSAGE_COUNT, messageService.receiveMessageCount(user.getId()));
			success(SUCCESS);
		} catch (Exception e) {
			error(PASSWORD_ERROR);
		}
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout() {
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.logout();
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		return "redirect:/login";
	}

	private AuthenticationToken createToken(HttpServletRequest request) {
		String username = WebUtils.getCleanParam(request, "phone");
		String password = WebUtils.getCleanParam(request, "password");

		String passwordAsMd5 = Utility.md5md5(password);
		String rememberMeAsString = WebUtils.getCleanParam(request, "rememberMe");
		boolean rememberMe = false;
		if (null != rememberMeAsString) {
			rememberMe = Boolean.valueOf(rememberMeAsString);
		}
		String host = request.getRemoteHost();
//		return new UsernamePasswordUsertypeToken(username, passwordAsMd5, "1");
		return new UsernamePasswordToken(username, passwordAsMd5, rememberMe, host);
	}
	
	private void saveInvitation(String code, int userId){
		
		//邀请成员登录填写邀请码
		if(ToolUtil.isNotEmpty(code)) {
			Invitation invitation = invitationService.findInvitationByCode(code);
			if(null != invitation) {
				invitation.setSendStatus(2);
				invitation.setReceiveId(userId);
				invitation.setAcceptTime(Utility.getSimpleFormatedDayNow());
				invitationService.updateInvitation(invitation);
				userRoleService.saveUserRole(new UserRole(userId, invitation.getRoleId(), invitation.getInviteId()));
			}
		}
	}
}
